#!/bin/bash

# Docker 国内镜像源配置
declare -A MIRRORS=(
    ["aliyun"]="https://mirrors.aliyun.com/docker-ce"
    ["tsinghua"]="https://mirrors.tuna.tsinghua.edu.cn/docker-ce"
    ["ustc"]="https://mirrors.ustc.edu.cn/docker-ce/"
)

# 自动选择最优镜像（可手动指定）
SELECTED_MIRROR=${MIRRORS[aliyun]}

# 获取系统信息
OS_ID=$(grep -Po '(?<=^ID=).+' /etc/os-release | tr -d '"')
OS_VERSION=$(grep -Po '(?<=^VERSION_ID=).+' /etc/os-release | tr -d '"')

# 卸载旧版本
remove_old_docker() {
    echo "正在移除旧版本 Docker..."
    case $OS_ID in
        ubuntu|debian|kali)
            for pkg in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc; do sudo apt-get remove $pkg; done
            ;;
        centos|rhel|almalinux|rocky)
         # CentOS 8 以上使用 dnf
            if [[ $OS_VERSION =~ ^7 ]]; then
                PKG_MANAGER=yum
            else
                PKG_MANAGER=dnf
            fi
            sudo $PKG_MANAGER remove -y docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine podman runc
            ;;
        *)
            echo "不支持的发行版: $OS_ID"
            exit 1
            ;;
    esac
}

# 配置镜像源
configure_repo() {
    echo "配置 $SELECTED_MIRROR 镜像源..."
    case $OS_ID in
        ubuntu|debian|kali)
            if [[ $OS_ID = "kali" ]]; then
                OS_ID=debian
                lsb_release=bookworm
            else
                OS_ID=$OS_ID
                lsb_release=$(lsb_release -cs)
            fi
            # 安装依赖
            sudo apt-get update
            sudo apt-get install -y apt-transport-https ca-certificates curl gnupg

            # 添加 GPG 密钥
            curl -fsSL $SELECTED_MIRROR/linux/$OS_ID/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

            # 设置仓库

            echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] $SELECTED_MIRROR/linux/$OS_ID $lsb_release stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

            sudo apt-get update
            ;;
        centos|rhel|almalinux|rocky)
            # CentOS 8 以上使用 dnf
            if [[ $OS_VERSION =~ ^7 ]]; then
                PKG_MANAGER=yum
            else
                PKG_MANAGER=dnf
            fi

            sudo $PKG_MANAGER install -y yum-utils dnf-plugins-core
            sudo $PKG_MANAGER-config-manager --add-repo $SELECTED_MIRROR/linux/centos/docker-ce.repo

            # 替换变量适配版本
            sudo sed -i "s/\$releasever/$OS_VERSION/" /etc/yum.repos.d/docker-ce.repo
            ;;
        *)
            echo "不支持的发行版: $OS_ID"
            exit 1
            ;;
    esac
}

# 安装 Docker
install_docker() {
    echo "开始安装 Docker CE..."
    case $OS_ID in
        ubuntu|debian)
            sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
            ;;
        centos|rhel|almalinux|rocky)
            if [[ $OS_VERSION =~ ^7 ]]; then
                sudo yum install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
            else
                sudo dnf install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
            fi
            sudo systemctl enable --now docker
            ;;
    esac
}

# 配置Docker镜像源
configure_reg() {
    echo "开始配置 Docker 镜像源..."
    # 创建 Docker 配置目录
    sudo mkdir -p /etc/docker
    sudo tee /etc/docker/daemon.json <<EOF
    {
        "registry-mirrors": [
            "https://docker.1ms.run",
            "https://docker.xuanyuan.me"
        ]
    }
EOF
    # 重启Docker服务
    sudo systemctl daemon-reload
    sudo systemctl restart docker
}

# 配置用户组
setup_user_group() {
    read -p "输入要加入 docker 组的用户名（留空跳过）: " USERNAME
    if [[ -n $USERNAME ]]; then
        if id "$USERNAME" &>/dev/null; then
            sudo usermod -aG docker $USERNAME
            echo "用户 $USERNAME 已加入 docker 组，需要重新登录生效"
        else
            echo "用户 $USERNAME 不存在，跳过组配置"
        fi
    fi
}

# 主流程
main() {
    remove_old_docker
    configure_repo
    install_docker
    configure_reg

    # 启动服务
    sudo systemctl enable --now docker
    sudo systemctl start docker

    setup_user_group

    # 验证安装
    echo "Docker 版本信息："
    sudo docker version
    echo -e "\n运行测试容器："
    sudo docker run --rm hello-world
}

# 执行主函数
main
